﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class BackupPipe : UpdatePipeBase, IUpdatePipe
{
    public BackupPipe()
    {
        PipeName = "备份";
    }

    protected override Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        var backupPath = context.GetBackupDirectory();

        PathUtils.ForceDeleteDirectory(backupPath);

        var files = Directory
            .EnumerateFiles(context.WorkingDirectory, "*", SearchOption.AllDirectories)
            .Where(a => !a.EndsWith(Constants.LogFile, StringComparison.OrdinalIgnoreCase))
            .ToList();

        for (var i = 0; i < files.Count; i++)
        {
            var file = files[i];
            PathUtils.MoveToSubDirectory(context.WorkingDirectory, file, backupPath);
            context.ReportProgress(i + 1, files.Count);
        }
        context.Backuped = true;
        return Task.CompletedTask;
    }
}
